package com.videoaggre.zcl.api

import android.content.Context
import android.content.Intent
import androidx.lifecycle.Observer
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.LoadService
import com.videoaggre.zcl.bean.ResultBean
import com.videoaggre.zcl.common.toastMessageLong
import com.videoaggre.zcl.helper.loadsir.ErrorCallback
import com.videoaggre.zcl.helper.loadsir.LoadingCallback
import com.videoaggre.zcl.helper.loadsir.NotNetworkCallback
import com.videoaggre.zcl.ui.dialog.LoadingDialog
import com.videoaggre.zcl.ui.widget.CommonButton
import com.videoaggre.zcl.utils.ActivityManger
import com.videoaggre.zcl.utils.Logger
import com.videoaggre.zcl.utils.Utils
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.videoaggre.zcl.helper.RefreshListener
import com.videoaggre.zcl.helper.SmartRefreshListener
import org.lzh.framework.updatepluginlib.util.SafeDialogHandle
import java.io.IOException
import java.net.SocketException


/**
 * 接口请求处理类
 */
open class ApiObserver<T>(
    private var context: Context? = null,
    private var dialog: LoadingDialog? = null,
    private val cancelable: Boolean = true,
    private val showMsg: Boolean = true,
    private val showLoadingDialog: Boolean = true,
    private var commonButton: CommonButton? = null,
    private var loadService: LoadService<*>? = null,
    refreshLayout: RefreshLayout? = null,
    private var error: ((Throwable?) -> Boolean)? = null,
    private var complete: (() -> Unit)? = null,
    private var success: ((T?) -> Unit)? = null
) : Observer<ApiProcess<T>> {
    private var refreshListener: RefreshListener? = null

    init {
        if (refreshLayout != null) refreshListener = SmartRefreshListener(refreshLayout)
    }

    override fun onChanged(apiProcess: ApiProcess<T>) {
        when (apiProcess.apiCode) {
            ApiCode.START -> {
                start()
            }
            ApiCode.SUCCESS -> {
                success(apiProcess.data)
            }
            ApiCode.ERROR -> {
                onError(apiProcess.throwable)
            }
            ApiCode.COMPLETE -> {
                onComplete()
            }
        }
    }

    open fun start() {
        if (loadService != null && loadService!!.currentCallback !== SuccessCallback::class.java) {
            loadService?.showCallback(LoadingCallback::class.java)
        } else {
            try {
                if (dialog == null && context != null && showLoadingDialog) {
                    dialog = LoadingDialog(context!!)
                    dialog?.setCancelable(cancelable)
                }
                SafeDialogHandle.safeShowDialog(dialog)
            } catch (e: Exception) {
                Logger.e(e)
            }
        }
        commonButton?.enable(false)
    }

    open fun success(t: T?) {
        try {
            loadService?.showSuccess()
            success?.invoke(t)
            dismiss()
        } catch (e: Exception) {
            onError(e)
        }
    }

    open fun onError(e: Throwable?) {
        refreshListener?.stopRefresh()
        if (error == null || false == error?.invoke(e)) {
            try {
                if (showMsg) {
                    if (e is FirmException) {
                        if (!doFirmError(e) && !Utils.isEmpty(e.message)) {
                            toastMessageLong(if (e.message!!.length > 100) " 服务器异常" else e.message)
                        }
                    } else if (e is IOException || e is SocketException) {
                        toastMessageLong("网络连接失败")
                    } else if ("kotlinx.coroutines.JobCancellationException" == e?.javaClass?.name) {
                        //toastMessageLong("网络连接失败")
                    } else {
                        toastMessageLong("加载未成功")
                    }
                }
                if (e is FirmException) {
                    if (ResultBean.NOT_LOGIN == e.code) {
                        try {
//                        if (!LoginActivity.isStart) {
//                            LoginActivity.isStart = true
//                            val activity = ActivityManger.getCurActivity()
//                            activity.startActivity(Intent(activity, LoginActivity::class.java).apply {
//                                putExtra(LoginActivity.KEY_SOURCE, LoginActivity.SOURCE_API_NOT_LOGIN)
//                                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                            })
//                        }
                        } catch (ec: Exception) {
                            Logger.e("启动登录失败")
                        }
                    }
                }
                Logger.e(e)
                if (!doError(e)) {
                    if (loadService != null) {
                        if (e is NotNetworkException) {
                            loadService?.showCallback(NotNetworkCallback::class.java)
                        } else loadService?.showCallback(ErrorCallback::class.java)
                    }
                }
            } catch (e1: Exception) {
                Logger.e(e1)
            }
        }
        dismiss()
    }

    open fun onComplete() {
        complete?.invoke()
        refreshListener?.stopRefresh()
        commonButton?.enable(true)
    }

    /**
     * @return 业务异常是否已被处理
     */
    open fun doFirmError(e: FirmException): Boolean {
        return false
    }

    /**
     * 子类自己处理异常
     */
    open fun doError(e: Throwable?): Boolean = false

    fun onDismiss() {}

    fun dismiss() {
        SafeDialogHandle.safeDismissDialog(dialog)
        onDismiss()
    }

    fun onDestroy() {
        dismiss()
        success = null
        context = null
        dialog = null
        loadService = null
        refreshListener = null
        commonButton = null
    }
}